<template>
	<el-card>
		<el-button type="primary" :icon="Plus">添加用户</el-button>

		<el-table :data="userList" border class="table">
			<el-table-column label="序号" type="index" align="center" width="60" />
			<el-table-column prop="username" label="用户名" />
			<el-table-column prop="roleName" label="权限值" />
			<el-table-column label="操作" width="300">
				<!-- 必须加上#default -->
				<template #default>
					<el-button type="warning" size="small"> 更新用户 </el-button>
					<el-button type="primary" size="small"> 分配用户权限 </el-button>
					<el-button type="danger" size="small"> 删除用户 </el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 
			v-model:xxx="xxx" 用于双向数据绑定（父 <-> 子）
				可以设置多个v-model，对多个数据进行双向数据绑定
		-->
		<el-pagination
			v-model:currentPage="currentPage"
			v-model:page-size="pageSize"
			:page-sizes="[5, 10, 15, 20]"
			layout="prev, pager, next, jumper, sizes, total"
			:total="total"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		/>
	</el-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
/*
	引入即暴露
	将所有图标拆分成一个个组件使用，实现按需加载
*/
import { Plus } from "@element-plus/icons-vue";
// 引入请求接口函数
import { reqGetUserList } from "./api/user"; // 不能写ts文件扩展名

import { UserList } from "./types";

// 定义ts的类型，只需要定义自己的数据
// 定义响应式数据
// const userList = ref([{}]);
// const currentPage = ref<number>(1);
// const pageSize = ref<number>(5);
// const total = ref<number>(0);

// const handleSizeChange = (pageSize: number): void => {};
// const handleCurrentChange = (currentPage: number): void => {};
const userList = ref<UserList>([]); // 将来需要定义其类型
const currentPage = ref(1); // 类型推论为number，就不需要定义了
const pageSize = ref(5);
const total = ref(0);

// 生命周期函数
onMounted(() => {
	getUserList();
});

// 公共发送请求的函数
const getUserList = async () => {
	// 使用ref数据的值，需要.value
	const res = await reqGetUserList(currentPage.value, pageSize.value);
	// console.log(res);
	total.value = res.data.data.total;
	userList.value = res.data.data.items;
};

// 类型推论为any，不行，需要定义
const handleSizeChange = (limit: number) => {
	pageSize.value = limit;
	getUserList();
};
const handleCurrentChange = (page: number) => {
	currentPage.value = page;
	getUserList();
};
</script>

<style>
.table {
	margin: 10px 0;
}
</style>
